package com.du.dupload;

/**
 * Manually written background data loader. Loads text from the reader passed
 * and puts it to the UI through the callback passed. Note, that loader can be
 * executed only once.
 *
 * @author Eugene Matyushkin aka Skipy
 * @version $Id: CustomLoader.java 416 2010-07-26 14:22:39Z skipy_ru $
 * @since 09.07.2010
 */
public class CustomLoader implements Runnable, ILoader {

	/**
	 * Execution flag
	 */
	private boolean executed = false;

	/**
	 * UI callback
	 */
	protected IUICallback ui;

	/**
	 * Data source
	 */
	private IResourceDownloader reader;

	/**
	 * Loader cancelation flag
	 */
	private boolean canceled = false;

	/**
	 * Created custom loader.
	 *
	 * @param ui
	 *            UI callback to use when publishing data and manipulating UI
	 * @param reader
	 *            data source
	 */

	private ManagerCallback mc;

	public CustomLoader(IUICallback ui, IResourceDownloader reader,
			ManagerCallback mc) {
		this.ui = ui;
		this.reader = reader;
		this.mc = mc;
	}

	/**
	 * Starts this loader execution in separate thread
	 */
	@Override
	public synchronized void execute() throws IllegalStateException {
		if (executed) {
			throw new IllegalStateException("Loader is already executed");
		}
		executed = true;
		Thread t = new Thread(this, "Custom loader thread");
		t.start();
	}

	/**
	 * Loader main cycle
	 */
	@Override
	public void run() {
		reader.initializeLoading();
		reader.startDownload();
		ui.startLoading("Loading files");
		StringBuilder sb = new StringBuilder();
		float cur;
		while (!isCanceled()) {
			// String str = reader.getNextLine();
			if (reader.isCompleted() || reader.isError()) {
				break;
			}
			cur = reader.getProgressPercent();
			
			// sb.append(str).append("\n");
			ui.setProgress(cur);
			ui.setItemName(reader.getName());
			// ui.appendText(str + "\n");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException ex) {
				// Logger.getLogger(DownloadTorrent.class.getName()).log(Level.SEVERE,
				// null, ex);
			}
		}
		// ui.setText(sb.toString());
		// ui.stopLoading();
		reader.stopDownload();
		reader.close();

		if (reader.isError() || isCanceled()) {
			mc.taskDisrupted("");
		}
		if (reader.isCompleted()) {
			mc.setSplitData(reader.getPath());
			mc.currentTaskIsFinished("Loaded");
		}
	}

	/**
	 * Cancels current loading
	 */
	public synchronized void cancel() {
		canceled = true;
		reader.stopDownload();
	}

	/**
	 * Checks whether execution was cancelled
	 *
	 * @return check result
	 */
	private synchronized boolean isCanceled() {
		return canceled;
	}
}
